package com.example.springboot1.utils;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

 public class HttpKit {

    public static String getRemoteHost(){
       return HttpKit.getRequest().getRemoteHost();
    }

    /**
     * 获取响应流
     * @return
     */
    public static OutputStream getResponseOutputStream(){
        try {
            return HttpKit.getResponse().getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new BussinessException("获取响应流失败");
        }
    }

    /**
     * 获取所有请求的值
     */
    public static Map<String, String> getRequestParameters() {
        HashMap<String, String> values = new HashMap<>();
        HttpServletRequest request = HttpKit.getRequest();
        Enumeration<?> enums = request.getParameterNames();
        while ( enums.hasMoreElements()){
            String paramName = (String) enums.nextElement();
            String paramValue = request.getParameter(paramName);
            values.put(paramName, paramValue);
        }
        return values;
    }

    /**
     * 获取 HttpServletRequest
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 获取 HttpServletRequest
     * @return request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获取header
     * @return
     */
    public static String getHeader(String name) {
        return HttpKit.getRequest().getHeader(name);
    }

    /**
     * 获取header
     * @return
     */
    public static void setDownloadHeaders(String fileName, byte[] bytes) {
        try {
            String userAgent= HttpKit.getRequest().getHeader("User-Agent");
            // IE，Edge浏览器
            if (userAgent.toLowerCase().indexOf("trident") > -1
                    || userAgent.toLowerCase().indexOf("edge") > -1) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            HttpServletResponse response = HttpKit.getResponse();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);
            response.setCharacterEncoding("utf-8");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BussinessException("下载异常");
        }
    }

    public static String getIpAddress(HttpServletRequest  request)  {
        if(request == null) return getRemoteHost();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0  || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length()  ==  0 || "unknown".equalsIgnoreCase(ip)) {
            ip  =  request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length()  ==  0 || "unknown".equalsIgnoreCase(ip)) {
            ip  =  request.getRemoteAddr();
        }
         if (ip.contains(","))  {
            return  ip.split(",")[0];
        }
        else {
            return  ip;
        }

    }
}
